<!--vue模板-->
<template>
    <div class="bg">
    <div class="login-box">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>登录面板</span>
                </div>
            </template>

            <!-- 登录表单 -->
            <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="90px" class="userForm" size="large"
                status-icon>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" placeholder="请输入用户名" />
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" type="password" placeholder="请输入密码"/>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm(userFormRef)">
                        登录 
                    </el-button>
                    <el-button @click="resetForm(userFormRef)">重置</el-button>
                </el-form-item>

            </el-form>

        </el-card>
    </div>
</div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { reactive, ref } from 'vue'
import userApi from '@/api/UserApi'
import { useRouter } from 'vue-router';
import { saveUserInfo, saveToken } from '@/util/auth'

// 获取表单对象
const userFormRef = ref(null)

// 定义用户登录的表单
const userForm = reactive({
    username: "",
    password: ""
})

// 定义校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '用户名错误', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 15, message: '密码错误', trigger: 'blur' },
    ]
}
// 获取路由对象
const router = useRouter();

// 提交表单
const submitForm = (formRef) => {
    formRef.validate(val => {
        console.log(val)
        // 验证通过
        if(val) {
            userApi.login(userForm).then(resp => {
                // 获取user信息 以及 token信息 通过LocalStorage存储起来
                saveUserInfo(resp.data.user)
                saveToken(resp.data.token)
                router.push("/")         
            })
        }

        // 验证失败
    })
}

// 清空表单
const resetForm = (formRef) => {
    console.log(formRef,"formRef");
    formRef.resetFields()
}


</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>

.login-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.card-header {
    text-align: center;
    font-size: 1.125rem;
}

.bg {
    width: 100vw;
    height: 100vh;
    background: url('https://cdn.seovx.com/ha/?mom=302') no-repeat 100%/cover;
}

.text {
    font-size: 16px;
}

.item {
    margin-bottom: 18px;
}

.box-card {
    width: 780px;
    background: transparent;
    color: aliceblue;
}
:deep(.el-form-item__label) {
    color: white;
}
</style>